﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using BaHuan.BusinessLayer;
using BaHuan.Common;
using BaHuan.Entities;
namespace BaHuan
{
    public partial class FrmDinhKhoanPhieuNhapKho : Form
    {
        public event FormClosePhieuNhapKhoEventHandler formclosePhieuNhapKho = null;
        private TaiKhoanKeToanMgt taikhoanketoanMgt = new TaiKhoanKeToanMgt();
        private ChiNhanhCongTyMgt chinhanhcongtyMgt = new ChiNhanhCongTyMgt();
        private ButToanMgt buttoanMgt = new ButToanMgt();
        private BangKeNhapHangMgt bangkenhaphangMgt = new BangKeNhapHangMgt();

        public long tien = 0;
        public long tongtien = 0;

        private PhieuNhapKho phieunhapkho;
        public PhieuNhapKho PhieuNhapKho
        {
            set { this.phieunhapkho = value;}
            get{return this.phieunhapkho;}
        }

        private BangKeNhapHang bangkenhaphang;
        public BangKeNhapHang BangKeNhapHang
        {
            set { this.bangkenhaphang = value; }
            get { return this.bangkenhaphang; }
        }

        public FrmDinhKhoanPhieuNhapKho(PhieuNhapKho phieunhapkho, long tient)
        {
            InitializeComponent();
            this.PhieuNhapKho = phieunhapkho;
            this.tongtien = tient;
        }

        private void FrmDinhKhoanPhieuNhapKho_Load(object sender, EventArgs e)
        {
            ChangeStatusTextBox(true);
            txtSoChungTu.Text = phieunhapkho.MaSo;

            ResultObj result = new ResultObj();
            result = bangkenhaphangMgt.GetAllBangKeNhapHang();

            BangKeNhapHang bangkenhaphang = (from bk in (List<BangKeNhapHang>)result.Result
                                             where bk.Id == this.phieunhapkho.IdBangKe && bk.IsDelete == 0
                                             select bk).FirstOrDefault();

            txtMSKH.Text = bangkenhaphang.NhaCungCap;
            txtNoiDung.Text = phieunhapkho.NoiDung;

            ResultObj rs = new ResultObj();
            rs = chinhanhcongtyMgt.GetAllChiNhanhCongTy();

            ChiNhanhCongTy chinhanhcongty = (from cn in (List<ChiNhanhCongTy>)rs.Result
                                             where cn.Id == this.phieunhapkho.IdChiNhanhCTy && cn.IsDelete == 0
                                             select cn).FirstOrDefault();

            txtChiNhanh.Text = chinhanhcongty.TenChiNhanh;

            cboSoTK.DataSource = GetAllTaiKhoanKeToan();
            cboSoTK.DisplayMember = "MaSoTK";
            cboSoTK.ValueMember = "Id";

            dgvDinhKhoan.Columns["colSoTien"].ReadOnly = false;
        }

        public void ChangeStatusTextBox(bool IsReadOnly)
        {
            if (IsReadOnly)
            {
                txtChiNhanh.ReadOnly = true;
                txtMSKH.ReadOnly = true;
                txtSoChungTu.ReadOnly = true;
            }
            else
            {
                txtChiNhanh.ReadOnly = false;
                txtMSKH.ReadOnly = false;
                txtSoChungTu.ReadOnly = false;
            }
        }

        private void btnLuu_Click(object sender, EventArgs e)
        {
            for (int i = 1; i < dgvDinhKhoan.Rows.Count - 1; i++)
            {
                if ((dgvDinhKhoan.Rows[i].Cells[0].FormattedValue.ToString() == "" || dgvDinhKhoan.Rows[i].Cells[1].FormattedValue.ToString() == "" ))
                {
                    MessageBox.Show("Vui lòng nhập đầy đủ thông tin trong danh sách !", "Thông báo");
                    return;
                }
            }

            if (tien == tongtien)
            {
                ResultObj resultObj = new ResultObj();

                int rowIndex = -1;
                for (int i = 0; i < dgvDinhKhoan.Rows.Count - 1; i++)
                {
                    if (dgvDinhKhoan.Rows[i].Cells[1].FormattedValue.ToString() == "Có")
                    {
                        rowIndex = i;
                        break;
                    }
                }

                if (rowIndex == -1)
                {
                    MessageBox.Show("Chưa chọn tài khoản có !!!", "Thông báo");
                    return;
                }

                for (int i = 0; i < dgvDinhKhoan.Rows.Count - 1; i++)
                {
                    if (i != rowIndex && dgvDinhKhoan.Rows[i].Cells[1].FormattedValue.ToString() == "Có")
                    {
                        dgvDinhKhoan.Rows[i].Cells[1].Value = "Nợ";
                    }
                }

                //check so tien
                for (int i = 0; i < dgvDinhKhoan.Rows.Count - 1; i++)
                {
                    if (dgvDinhKhoan.Rows[i].Cells[3].FormattedValue.ToString() == "")
                    {
                        MessageBox.Show(string.Format("Chưa nhập tiền cho tài khoản {0} !!!", dgvDinhKhoan.Rows[i].Cells[0].FormattedValue.ToString()), "Thông báo");
                        return;
                    }
                }

                EditOrRemoveDinhKhoan(phieunhapkho.MaSo);

                //Save
                for (int i = 0; i < dgvDinhKhoan.Rows.Count - 1; i++)
                {
                    if (i != rowIndex && dgvDinhKhoan.Rows[i].Cells[3].FormattedValue.ToString() != "0")
                    {
                        ButToan buttoan = new ButToan();
                        buttoan.NgayThang = dtpNgay.Value;
                        buttoan.ChiNhanh = txtChiNhanh.Text;
                        buttoan.MaSoKhachHang = txtMSKH.Text;
                        buttoan.DienGiai = txtNoiDung.Text;
                        buttoan.SoChungTu = txtSoChungTu.Text;
                        buttoan.TKGoc = dgvDinhKhoan.Rows[rowIndex].Cells[0].FormattedValue.ToString();
                        buttoan.TKDoiUng = dgvDinhKhoan.Rows[i].Cells[0].FormattedValue.ToString();
                        buttoan.GhiNo = 0;
                        buttoan.GhiCo = Convert.ToInt64(dgvDinhKhoan.Rows[i].Cells[3].Value.ToString());
                        resultObj = buttoanMgt.SaveNewButToan(buttoan);

                        buttoan = new ButToan();
                        buttoan.NgayThang = dtpNgay.Value;
                        buttoan.ChiNhanh = txtChiNhanh.Text;
                        buttoan.MaSoKhachHang = txtMSKH.Text;
                        buttoan.DienGiai = txtNoiDung.Text;
                        buttoan.SoChungTu = txtSoChungTu.Text;
                        buttoan.TKGoc = dgvDinhKhoan.Rows[i].Cells[0].FormattedValue.ToString();
                        buttoan.TKDoiUng = dgvDinhKhoan.Rows[rowIndex].Cells[0].FormattedValue.ToString();
                        buttoan.GhiNo = Convert.ToInt64(dgvDinhKhoan.Rows[i].Cells[3].Value.ToString());
                        buttoan.GhiCo = 0;
                        resultObj = buttoanMgt.SaveNewButToan(buttoan);
                    }
                }

                if (resultObj.ReturnCode > 0)
                {
                    MessageBox.Show("Lưu thành công", "Thông báo");
                    this.Close();
                    if (formclosePhieuNhapKho != null)
                        formclosePhieuNhapKho();
                }
                else if (resultObj.ReturnCode == Definitions.DUPLICATED_VALUE)
                    MessageBox.Show("Dữ liệu bị trùng", "Thông báo");
                else
                    MessageBox.Show("Thất bại");
            }
            else
            {
                MessageBox.Show("Số tiền định khoản không đúng", "Thông báo");
            }
            
        }

        public void EditOrRemoveDinhKhoan(string MaSo)
        {
            ResultObj resultObj = new ResultObj();

            List<ButToan> lst = (from p in GetAllButToan()
                                 where p.SoChungTu == MaSo
                                 select p).ToList();

            if (lst.Count > 0)
            {
                foreach (ButToan b in lst)
                {
                    b.IsEdited = 1;
                    resultObj = buttoanMgt.UpdateButToan(b);
                }
            }
        }

        public List<ButToan> GetAllButToan()
        {
            ResultObj resultObj = new ResultObj();

            resultObj = buttoanMgt.GetAllButToan();
            List<ButToan> listButToan = (List<ButToan>)resultObj.Result;

            return listButToan;
        }

        public List<TaiKhoanKeToan> GetAllTaiKhoanKeToan()
        {
            ResultObj resultObj = new ResultObj();

            List<TaiKhoanKeToan> lstTaiKhoanKeToan = new List<TaiKhoanKeToan>();

            resultObj = taikhoanketoanMgt.GetAllTaiKhoanKeToan();
            lstTaiKhoanKeToan = (List<TaiKhoanKeToan>)resultObj.Result;

            return lstTaiKhoanKeToan;
        }

        private void dgvDinhKhoan_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 3  && e.RowIndex > -1)
            {
                long num;
                if (!Int64.TryParse(dgvDinhKhoan.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString(), out num))
                {
                    MessageBox.Show("Vui lòng nhập số !", "Thông báo");
                    dgvDinhKhoan.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = 0;
                    return;
                }
            }

            if (e.ColumnIndex == 0 && e.RowIndex > -1)
            {
                ResultObj result = new ResultObj();

                List<TaiKhoanKeToan> lstTaiKhoanKeToan = (from tkkt in GetAllTaiKhoanKeToan()
                                                          where tkkt.Id == Convert.ToInt32(dgvDinhKhoan.Rows[e.RowIndex].Cells[0].Value.ToString())
                                                          select tkkt).ToList();

                string tenTK = lstTaiKhoanKeToan[0].TenTK;

                dgvDinhKhoan.Rows[e.RowIndex].Cells[2].Value = tenTK;
                int soDinhKhoan = Convert.ToInt32(dgvDinhKhoan.Rows[e.RowIndex].Cells[0].FormattedValue.ToString());
                long tongThanhTien = 0;
                long tongMotBaBaMot = 0;

                for(int i = 0; i < phieunhapkho.listCTPhieuNhapKho.Count; i++)
                {
                    tongThanhTien += phieunhapkho.listCTPhieuNhapKho[i].ThanhTien;
                }

                switch (soDinhKhoan)
                {
                    case 1331:
                        tongMotBaBaMot = Convert.ToInt64(Math.Ceiling((double)tongThanhTien * phieunhapkho.Thue / 100));
                        dgvDinhKhoan.Rows[e.RowIndex].Cells[3].Value = tongMotBaBaMot;
                        break;
                    default:
                        dgvDinhKhoan.Rows[e.RowIndex].Cells[3].Value = 0;
                        break;

                }                
            }
            if (e.ColumnIndex == 3 && e.RowIndex > -1 && dgvDinhKhoan.Rows[e.RowIndex].Cells[1].FormattedValue.ToString() != "Nợ")
            {
                if (dgvDinhKhoan.Rows[e.RowIndex].Cells[3].Value == null)
                    dgvDinhKhoan.Rows[e.RowIndex].Cells[3].Value = 0;
            }

            long tongcong = 0;
            for (int j = 0; j < dgvDinhKhoan.Rows.Count - 1; j++)
            {
                if (dgvDinhKhoan.Rows[j].Cells[1].FormattedValue.ToString() != "Có" && dgvDinhKhoan.Rows[j].Cells[3].Value != null)
                {
                    tongcong += Convert.ToInt64(dgvDinhKhoan.Rows[j].Cells[3].Value.ToString());
                }
            }

            tien = tongcong;
        }

        private void btnThoat_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void dgvDinhKhoan_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            e.Cancel = false;
        }

        private void XoaToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (dgvDinhKhoan.CurrentRow != null)
            {
                if (dgvDinhKhoan.CurrentRow.Index != (dgvDinhKhoan.Rows.Count - 1))
                {
                    dgvDinhKhoan.Rows.RemoveAt(dgvDinhKhoan.CurrentRow.Index);
                    long sotien = Convert.ToInt64(dgvDinhKhoan.Rows[dgvDinhKhoan.CurrentRow.Index].Cells[3].Value.ToString());
                    for (int i = 0; i < dgvDinhKhoan.Rows.Count; i++)
                    {
                        if (dgvDinhKhoan.Rows[i].Cells[0].FormattedValue.ToString() == "331")
                        {
                            long sotien331 = Convert.ToInt64(dgvDinhKhoan.Rows[i].Cells[3].Value.ToString());
                            long result = sotien331 - sotien;
                            this.tongtien = result;
                            dgvDinhKhoan.Rows[i].Cells[3].Value = result;
                            break;
                        }
                    }
                }
            }
        }

        private void dgvDinhKhoan_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Right)
            {
                DataGridView.HitTestInfo hti = dgvDinhKhoan.HitTest(e.X, e.Y);
                if (hti.Type == DataGridViewHitTestType.Cell)
                {
                    dgvDinhKhoan.ClearSelection();
                    dgvDinhKhoan.CurrentCell = dgvDinhKhoan.Rows[e.RowIndex].Cells[e.ColumnIndex];
                    dgvDinhKhoan.ContextMenuStrip = contextMenuStrip1;
                }
            }
        }
    }
}
